/**
 * 
 */
package com.application.Activity;

import java.util.ArrayList;

import it.unipr.ce.dsg.s2p.sip.Address;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Controller.ReadWriteFileController;
import com.application.DTO.AccountDTO;
import com.application.DataProvider.AccountDAO;
import com.application.DataProvider.LearnerDAO;

/**
 * @author TAI
 * 
 */
public class FrmLogin extends Activity {
	EditText _txtUsername;
	EditText _txtPassword;
	private static String _pass;
	CheckBox _chkRemember;
	private static ProgressDialog _dialog;
	Button _btnLogin;
	LinearLayout _llo_banner;
	Address _address;
	AccountDAO aDao = new AccountDAO(null);
	private static final int EDIT_ID = Menu.FIRST+2;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.frm_dangnhap);

		SharedPreferences prefs=PreferenceManager
		.getDefaultSharedPreferences(this);
		String ip = prefs.getString(PrefActivity.PREF_SET_UP_IP_HOST, "192.168.2.1");
		ip+= ":5033";
		NetworkController.set_ipHost(ip);

		NetworkController.set_isOffline(prefs.getBoolean(PrefActivity.PREF_SET_UP_OFFLINE, false));	

		_txtUsername=(EditText)findViewById(R.id.frmdangnhap_txtusername);
		_txtPassword=(EditText)findViewById(R.id.frmdangnhap_txtpassword);
		_chkRemember=(CheckBox)findViewById(R.id.frmdangnhap_chkremember);

		_btnLogin=(Button)findViewById(R.id.frmdangnhap_btndangnhap);
		_btnLogin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String userName=_txtUsername.getText().toString();
				String pass=_txtPassword.getText().toString();
				_pass = pass;

				/*lưu nhớ account*/
				//ghi thông tin xuống file nếu check ghi nhớ
				if(_chkRemember.isChecked())
					ReadWriteFileController.WriteAccount(userName, pass, true);
				else
					ReadWriteFileController.WriteAccount(userName, pass, false);
				//	FrmSubject.set_isWait(true);

				if(NetworkController.isOffline())
				{
					Log.d("PEERDROID", "offline");
					//					String path = Environment.getExternalStorageDirectory().toString()+"/"+userName +".xml";
					//					//Kiểm tra userName có tồn tại
					//					if(ReadWriteFileController.isFile(path))
					//					{
					//						Log.d("PEERDROID", "offline");
					//						String uName = ReadXML.getTextValue(path, "Learner", "Username");
					//						String sPass = ReadXML.getTextValue(path, "Learner", "Pass");
					//						int idClass = ReadXML.getIntValue(path, "IDClass");
					//
					//						Log.d("PEERDROID", "UserNAme:" + uName);
					//						Log.d("PEERDROID", "pass:" + sPass);
					//						Log.d("PEERDROID", "IDClass:" + idClass);
					//						if(userName.equals(uName) && pass.equals(sPass))
					//						{
					//							startActivity(new Intent(getBaseContext(),FrmTabActivity.class));
					//							NetworkController.set_idClass(idClass);
					//							NetworkController.set_userName(userName);
					//						}
					//						else
					//							ShowLoginFail();
					//					}
					if(aDao.isExist(userName))
					{
						String uName = userName;
						String sPass = aDao.getPass(uName);

						LearnerDAO lDao = new LearnerDAO(null);
						int idClass = lDao.getIDClass(userName);

						Log.d("PEERDROID", "UserNAme:" + uName);
						Log.d("PEERDROID", "pass:" + sPass);
						Log.d("PEERDROID", "IDClass:" + idClass);
						if(userName.equals(uName) && pass.equals(sPass))
						{
							startActivity(new Intent(getBaseContext(),FrmTabActivity.class));
							NetworkController.set_idClass(idClass);
							NetworkController.set_userName(userName);
						}
						else
							ShowLoginFailOffline();
					}
					else
						ShowLoginFailOffline();
				}
				else
				{
					String s=NetworkController.get_ipHost();
					_address = new Address(s);
					if(userName.equals(""))
						ShowError();
					else
						if(pass.equals(""))
							ShowError();
						else{
							Log.d("PEERDROID","tao peer");
							NetworkController.init("DangNhap", 5033);
							Log.d("PEERDROID", "Bat dau send ID cho giao vien");
							NetworkController.Login(_address, userName, pass);

							final String uName = userName;
							final String password = pass;
							set_dialog(ProgressDialog.show(FrmLogin.this, "","Connecting ...", true));
							CountDownTimer timer = new CountDownTimer(15000, 1000) {
								@Override
								public void onTick(long millisUntilFinished) {
									
									Thread bg =  new Thread(new Runnable() {
										@Override
										public void run() {
											try {	
												
												if(NetworkController.is_isLogin()==2)
												{
													NetworkController.set_isLogin(3);
													if(!aDao.isExist(uName))
													{
														aDao.insertAccount(uName, password);
													}
													Log.i("Phu","success");
													//tạo các thư mục cần thiết cho ứng dụng:
//													NetworkController.get_threadConnectToUser().start();
													Log.d("PEERDROID","count thread login: " + Thread.activeCount());
													ReadWriteFileController.createDirectionFolder();
													NetworkController._peer.account=new AccountDTO();
													NetworkController._peer.account.set_Username(uName);
													NetworkController._peer.account.set_Password(password);
													startActivity(new Intent(getBaseContext(),FrmTabActivity.class));						 						
													finish();
													Log.i("Phu","finish");
												}
											}
											catch (Throwable t) {
												Log.d("PEERDROID","Loi Login " + t.getMessage());
											}
										}
									});
									bg.start();
								}
								@Override
								public void onFinish() {					    	 
									if(NetworkController.is_isLogin() == 0)
									{
										get_dialog().dismiss();
										ShowConnectFail();
									}
									if(NetworkController.is_isLogin()==1)
									{
										NetworkController.set_isLogin(0);
										get_dialog().dismiss();
										ShowLoginFail();
									}						    	  					        
								}
							}.start();
						}
					}
				}
			});
		}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(Menu.NONE, EDIT_ID, Menu.NONE, "Cài đặt đăng nhập")
		.setIcon(R.drawable.setting_host_ip)
		.setAlphabeticShortcut('e');
		return(super.onCreateOptionsMenu(menu));
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case EDIT_ID:
			startActivity(new Intent(this, PrefActivity.class));
			return(true);

		}
		return super.onOptionsItemSelected(item);
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
//			if(NetworkController.is_isLogin()==2)
//				NetworkController.SendMessageLogout();
//			NetworkController.set_isLogin(0);
			//			if(!NetworkController.isOffline())
			//				NetworkController.peerRelease();

			String userName=_txtUsername.getText().toString();
			String pass=_txtPassword.getText().toString();
			if(_chkRemember.isChecked())
				ReadWriteFileController.WriteAccount(userName, pass, true);
			else
				ReadWriteFileController.WriteAccount(userName, pass, false);

			Log.d("PEERDROID","Đã thoát khỏi chương trình");
			finish();
			System.exit(0);
		}
		return super.onKeyDown(keyCode, event);
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();		
		SharedPreferences prefs=PreferenceManager
		.getDefaultSharedPreferences(this);
		String ip = prefs.getString(PrefActivity.PREF_SET_UP_IP_HOST, "192.168.2.1");
		ip+= ":5033";
		NetworkController.set_ipHost(ip);

		NetworkController.set_isOffline(prefs.getBoolean(PrefActivity.PREF_SET_UP_OFFLINE, false));	

	}
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		if(!NetworkController.isOffline())
			if(NetworkController.get_peer() != null)
				NetworkController.peerRelease();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		//finish();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();		
	}
	private void ShowError()
	{
		AlertDialog.Builder alert=new AlertDialog.Builder(FrmLogin.this);
		alert.setTitle("Error");
		alert.setMessage("Tài khoản hoặc Mật Khẩu không được trống");
		alert.setPositiveButton("Đồng ý", null);
		alert.create().show();
	}

	private void ShowLoginFailOffline()
	{
		AlertDialog.Builder alert=new AlertDialog.Builder(FrmLogin.this);
		alert.setTitle("Error");
		alert.setMessage("Tài khoản hoặc Mật Khẩu không đúng");
		alert.setPositiveButton("Đồng ý", null);
		alert.create().show();
	}
	private void ShowLoginFail()
	{
		AlertDialog.Builder alert=new AlertDialog.Builder(FrmLogin.this);
		alert.setTitle("Error");
		alert.setMessage("Tài khoản hoặc Mật Khẩu không đúng");
		alert.setPositiveButton("Đồng ý", null);
		alert.create().show();
		//tắt peer
		Log.d("PEERDROID","tắt peer");
		NetworkController.peerRelease();
	}
	private void ShowConnectFail()
	{
		AlertDialog.Builder alert=new AlertDialog.Builder(FrmLogin.this);
		alert.setTitle("Error Connect");
		alert.setMessage("Kết nối không được tới máy chủ !");
		alert.setPositiveButton("Đồng ý", null);
		alert.create().show();
		//tắt peer
		Log.d("PEERDROID","Tắt peer");
		NetworkController.peerRelease();
	}
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		//lấy thông tin ip host để đăng nhập
		SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this);
		String ip = prefs.getString("txt_ip_host", "192.168.2.1");
		ip+= ":5033";
		NetworkController.set_ipHost(ip);
		NetworkController.set_isOffline(prefs.getBoolean(PrefActivity.PREF_SET_UP_OFFLINE, false));	
		//		if(!NetworkController.isOffline())
		//		{
		//
		//			if(NetworkController.get_peer()==null)
		//			{
		//				Log.d("PEERDROID","tao peer");
		//				NetworkController.init("DangNhap", 5033);
		//
		//			}
		//		}
		ActivityController.setPeerActivity(this);
		ArrayList<String> acc;
		Log.d("PEERDROID","load file");
		String path = Environment.getExternalStorageDirectory().toString()+"/account.xml";
		try {
			acc = ReadWriteFileController.ReadAccount(path);
			if(acc.size() != 0)
			{
				//if(acc.get(2).equals("true"))
				_chkRemember.setChecked(true);
				//else
				//_chkRemember.setChecked(false);

				if(_chkRemember.isChecked())
				{
					_txtUsername.setText(acc.get(0));
					_txtPassword.setText(acc.get(1));
				}
			}
			else
				_chkRemember.setChecked(false);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}

	public static void set_dialog(ProgressDialog _dialog) {
		FrmLogin._dialog = _dialog;
	}

	public static ProgressDialog get_dialog() {
		return _dialog;
	}

	public static void set_pass(String _pass) {
		FrmLogin._pass = _pass;
	}

	public static String get_pass() {
		return _pass;
	}


}



